﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Mvc4.Models;
using BussinesLayer.Services;
using DataAccess.Datatypes;

namespace Mvc4.Others
{
    public class RssReader
    {
        public static IEnumerable<Rss> GetRssFeed(string url, string keyword)
        {
            try
            {
                XDocument feedXml = XDocument.Load(url);
                List<Rss> feeds = new List<Rss>();
                foreach (var item in feedXml.Descendants("item"))
                {
                    string desc = item.Element("description").Value;
                    if (desc.ToLower().Contains(keyword))
                    {
                        try
                        {
                            Rss rss = new Rss();
                            rss.Title = item.Element("title").Value;
                            rss.Link = item.Element("link").Value;
                            desc = desc.Substring(0, 90);
                            int pos = desc.LastIndexOf(" ");
                            rss.Description = desc.Substring(0, pos) + "...";
                            feeds.Add(rss);
                        }
                        catch { }
                    }
                }

                return feeds.Take(5);
            }
            catch
            {
                return new List<Rss>();
            }
        }

    }
}